package com.leehom.arch.storage.exception;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.MessageFormat;

import lombok.Getter;

/**
 * @类名: FileStorageException
 * @说明: 文件存储异常
 *
 * @author   leehom
 * @Date	 2023年2月15日 下午2:12:27
 * 修改记录：
 *
 * @see 	 
 */
public class FileStorageException extends RuntimeException {

    private static final long serialVersionUID = 1L;
    
    private MessageCode MessageCode;

    // 带参数的消息
    public FileStorageException(MessageCode MessageCode, String... args) {
        super(MessageCode.toString() + " - " + MessageFormat.format(MessageCode.getMsg(), args));
        this.MessageCode = MessageCode;
    }
    
    public FileStorageException(MessageCode MessageCode) {
        super(MessageCode.toString());
        this.MessageCode = MessageCode;
    }

    public FileStorageException(String errorMessage) {
        super(errorMessage);
    }

    private FileStorageException(MessageCode MessageCode, Throwable cause) {
        super(MessageCode.toString() + " - " + getMessage(cause), cause);

        this.MessageCode = MessageCode;
    }

    public static FileStorageException asRbtException(MessageCode MessageCode, String message) {
        return new FileStorageException(MessageCode, message);
    }

    public static FileStorageException asRbtException(String message) {
        return new FileStorageException(message);
    }

    public static FileStorageException asRbtException(MessageCode MessageCode, Throwable cause) {
        if (cause instanceof FileStorageException) {
            return (FileStorageException) cause;
        }
        return new FileStorageException(MessageCode, cause);
    }

    public MessageCode getMessageCode() {
        return this.MessageCode;
    }

    private static String getMessage(Object obj) {
        if (obj == null) {
            return "";
        }

        if (obj instanceof Throwable) {
            StringWriter str = new StringWriter();
            PrintWriter pw = new PrintWriter(str);
            ((Throwable) obj).printStackTrace(pw);
            return str.toString();
            // return ((Throwable) obj).getMessage();
        } else {
            return obj.toString();
        }
    }
}
